import sqlite3
import logging

class DatabaseOps:
    def __init__(self, db_path):
        self.db_path = db_path

    def update_status_history(self, db_name, status, check_time, details):
        try:
            with sqlite3.connect(self.db_path) as conn:
                conn.execute(
                    "INSERT INTO status_history (db_name, status, check_time, details) VALUES (?, ?, ?, ?)",
                    (db_name, status, check_time, details)
                )
                conn.commit()
        except Exception as e:
            logging.error(f"更新状态历史失败: {str(e)}")

    def update_current_status(self, db_name, status, check_time, details):
        try:
            with sqlite3.connect(self.db_path) as conn:
                conn.execute(
                    "INSERT OR REPLACE INTO current_status (db_name, status, last_check_time, details) VALUES (?, ?, ?, ?)",
                    (db_name, status, check_time, details)
                )
                conn.commit()
        except Exception as e:
            logging.error(f"更新当前状态失败: {str(e)}")

    def check_status_recovery(self, db_name, status):
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute(
                    "SELECT status FROM current_status WHERE db_name=? ORDER BY last_check_time DESC LIMIT 1",
                    (db_name,)
                )
                last_record = cursor.fetchone()
                if last_record and last_record[0] == 'Failed' and status == 'OPEN':
                    cursor = conn.cursor()
                    cursor.execute(
                        "UPDATE current_status SET status = 'Recovered', details = '自动恢复于: ' || CURRENT_TIMESTAMP WHERE db_name = ?",
                        (db_name,)
                    )
                conn.commit()
                cursor.close()

        except Exception as e:
            logging.error(f"状态恢复检查失败: {str(e)}")